new Vue({
    el:'#main',
    data:()=>({
        tabType:$('#tab').val(),
        admin_id:$('#admin_id').val(),
        viewType:$('#requestType').val(),
        searchText:$('#searchText').val(),          // 产品产品的关键字
        orderList:[],            // 产品订单list
        orderListLength:0,            // 产品订单数量
        proInfoKey:-1,
        proInfo:[],
        saler:[],               // 业务员
        proCate:[],             // 产品分类list
        proCateId:0,            // 产品分类ID
        company:[],             // 公司
        companyInfo:{},         // 公司详情
        coSale:{                // 公司允许选择范围详情
            makefirst:0,
            pledge:0,
            pay_type_ids:'',
            delivery_id:0
        },              
        branchCompany:[],       // 分公司
        logisticsCompany:[],    // 物流公司
        saleDeliveryTypeList:[],// 送货方式
        saleCostType:[],        // 费用类型
        salePayType:[],         // 付款方式 
        quickInput:[],         // 快捷输入 
        receivingAccount:[],         // 收款账号 
        paymentList:[],         // 付款数据list
        paymentRemarksData:[],         // 付款安排备注
        paymentRemarksDataList:[],     // 付款安排数据list备注
        paydate:'',                    // 付款安排日期
        salePayreg:[],              // 付款登记
        salePayregRemarksData:[],              // 付款登记data
        saleOrderRemark:{},     // 订单备注     
        saleOrderRemarkData:[],  // 订单备注data list
        voucherList:[],         // 代金券
        voucherData:[],         // 使用时代金券table data
        voucherPriceSum:[],         // 使用的代金券合计金额
        data:{
            saler_id:0,             // 业务员Id
            priority:3,             // 优先级
            saleDeliveryTypeId:0,   // 送货方式
            saleOrderNo:'-',        // 订单编号
            companyId:0,            // 选中的公司Id
            branchCompanyId:0,      // 选中的分公司Id
            logisticsCompanyId:0,   // 选中的物流公司Id
            companySearchText:'',

            underwrite:false,       // 是否包销
            makefirst:false,        // 先配货后结算
            pledge:false,           // 是否需要定金

            receivingAccounId:0,     // 收款账号ID
            invoiceTypeId:0,
        },
        proCount:{              // 产品统计
            package_sum:0,
            m3:0,
            kgs:0,
            price:0
        },
        discountData:[],        // 折扣数据
        orderListKey:0,
        commissionData:[],       // 提成数据
        remarksData:[],         // 加工备注数据
        addRemarksData:[],
        costData:[],            // 费用数据  
        costDataLength:0,       // 费用数据数量  
        billDate:{              // 账单数据
            price:0,
            discountPrice:0,
            commissionPrice:0,
            costPrice:0,
            paymentPrice:0,
            payregPaid:0,       // 已付
            overdraft:0,        // 未付
        },             
        create_name:'',
        create_at:'',
        orderRemarkprivate:false,   // 销售订单是否私有状态
        bankList:[],            // 银行
        co_bank:[],            // 支付账号
        chequePriceSum:[],
        PayeryChequeData:[],
        transferPriceSum:[],
        payerytransferData:[],
        payregRemarkData:[],        // 付款快捷登记 备注head data 
        payregRemarkList:[],        // 付款快捷登记 备注table data 
        payregList:[],              // 付款登记 table list
        saleList:{                  // 销售订单主要详情数据
            create_time:this.create_at,
        },                

        payregAmount_:0,
        voucherData_:[],
        PayeryChequeData_:[],
        payerytransferData_:[],

        deliveryNoteHead:[],
        deliveryNoteDetailData:[],
        deliveryNoteList:[],
        deliveryNoteVolume:0,   // 送货单箱数
        deliveryNoteCtn:0,      // 送货单体积
        deliveryNoteRemarkContent:[], 


        publicInfo:[],           // 弹框公共数据
        proStoreStatusData:'',
        payregChequeInfo:{                // 登记数据
            chequeNoValue:'',
            chequeBankValue:-1,
            chequeSignature:'',
            chequeScan_url:'',
            chequeDay:this.create_at,
            chequePrice:0,
            chequeNoKey:-1,
            voucherId:-1,
            transferOutIdValue:-1,
            payreg_transfer_pay_dayValue:this.create_at,

            transferInIdValue:-1,

            transferPriceValue:'',
            transferNoValue:'',
            transferscan_url:'',
            transferKey:-1

        },
        getInvoiceTypeList:[],  // 发票类型
        delList:{},
        clearList:{},
        salePayBill:0,
        saleRecording:[],       // 采购记录    
        savePayeryPaytype_id:0,
        payeryIsEdit:-1,
        sale_payplan_id:0,
        saleLog:[],

        lastData:0,
        year:0,
        month:0,
        myDate:new Date,
        payregEdit:false,
        private:false,
        add:false,
        rationed:false,
        dayTime:'',
        proStatus:{
            status:{
                status:0,
                sale_qty_1y:0
            },
            storeType:{
                subWarehouseQty:0,
                storeQty:0,
            },
        },
        isdisabled:false,
        deliveryNoteDetailActive:'',
        fastPayrey_:false,
        fastPayrey_paytype_id:0,

    }),
    methods:{
        formatUnit:formatUnit,
        getdata(){
            this.point('','#alertMain','hide')
            $('.loding').show()
            if($('#requestType').val() == 'add'){
                var url = '/admin/sale/saleadd?request=add';
            }else{
                var url ='/admin/sale/saleEdit?request=edit&id='+ $('#edit_id').val()
            }
            $.ajax({
                url:url,
                type:'post',
                success:(data)=>{
                    data = JSON.parse(data)
                    if(data.status == 1 ){
                        this.saleDeliveryTypeList=data.data.saleDeliveryTypeList
                        this.proCate=data.data.proCate
                        this.saleCostType = data.data.saleCostType
                        this.quickInput = data.data.quickInput
                        this.receivingAccount = data.data.receivingAccount
                        this.salePayType = data.data.salePayType
                        if(this.viewType == 'edit'){
                            this.saleList = data.data.saleList
                            console.log(this.saleList)
                            this.data.saler_id = data.data.saleList.saler_id
                            this.data.priority = data.data.saleList.priority
                            this.data.saleDeliveryTypeId = data.data.saleList.delivery_type_id
                            this.data.saleOrderNo = data.data.saleList.id
                            this.data.companyId = data.data.saleList.co_id
                            this.data.branchCompanyId = data.data.saleList.co_branch_id
                            this.data.logisticsCompanyId = data.data.saleList.trans_id
                            this.data.underwrite = data.data.saleList.underwrite == 1 ? true : false 
                            data.data.saleList.underwrite == 1 ? $("input[name='underwrite']").attr("checked", "checked") :'';
                            this.data.makefirst = data.data.saleList.makefirst == 1 ? true : false 
                            data.data.saleList.makefirst == 1 ? $("input[name='makefirst']").attr("checked", "checked") :'';
                            this.data.pledge = data.data.saleList.pledge == 1 ? true : false 
                            data.data.saleList.pledge == 1 ? $("input[name='pledge']").attr("checked", "checked") :'';
                            this.data.receivingAccounId = data.data.saleList.accounts_id
                            if(this.data.receivingAccounId > 0) $('.receivingAccountItem').show();

                            this.data.invoiceTypeId = data.data.invoiceTypeId ? data.data.invoiceTypeId :0

                            // this.proCount.package_sum = data.data.saleList.ctn
                            // this.proCount.m3 = data.data.saleList.volume
                            // this.proCount.price = data.data.saleList.total

                            this.billDate.price = data.data.saleList.total
                            this.billDate.discountPrice = data.data.saleList.discount
                            this.billDate.costPrice = data.data.saleList.cost
                            this.billDate.commissionPrice = data.data.saleList.commission

                            this.company = data.data.company
                            this.companyInfo = data.data.companyInfo
                            this.branchCompany = data.data.branchCompany
                            this.logisticsCompany = data.data.logisticsCompany
                            this.saler = data.data.saler
                            this.saleOrderRemarkData = data.data.saleOrderRemarkData
                            this.orderList = data.data.orderList
                            this.costData = data.data.costData
                            this.paymentList = data.data.paymentList
                            this.salePayreg = data.data.paymentList
                            this.payregList = data.data.payregList
                            this.deliveryNoteList = data.data.deliveryNoteList
                            this.saleLog = data.data.saleLog

                            $.each(this.paymentList, (key1, value) => {
                                if(value.paytype_id == 6){
                                    this.salePayBill = 1;
                                    $('.receivingAccountItem').show();
                                } 
                            });
                            
                            this.getBank()
                            this.getCoBank()
                            this.getProCount('edit')
                        }
                    }else{
                        this.point(data.msg,'#alertMain','show',data.status)
                    }
                    $('.loding').hide()
                }
            })
        },
        selectDeliveryType(id,type=''){ // 获取物流公司信息
            this.logisticsCompany = []
            if(type == 'deliveryNote') id = $('#deliveryTypeId').val()
            if(id == 4){
                $.ajax({
                    url:'/admin/sale/searchCompany?request=wuliu',
                    type:'post',
                    success:(data)=>{
                        data = JSON.parse(data)
                        this.logisticsCompany = data.data
                    }
                })
            }
        },
        companySearch(){
            $.ajax({
                url:'/admin/sale/searchCompany?request=company',
                type:'post',
                data:{searchCompany:this.data.companySearchText},
                success:(data)=>{
                    data = JSON.parse(data)
                    this.company = data.data
                    if(data.data.length == 1){
                        this.data.companyId = data.data[0].id
                        this.getCompanyBranch()
                    }else{
                        this.data.companyId = 0
                    }
                }
            })
        },
        getCompanyBranch(){
            this.branchCompany = []
            $.ajax({
                url:'/admin/sale/searchCompany?request=branch',
                type:'post',
                data:{company_id:this.data.companyId},
                success:(data)=>{
                    data = JSON.parse(data)
                    this.branchCompany = data.data.branch
                    this.companyInfo = data.data.companyInfo.data
                    this.coSale = data.data.companyInfo.coSale.coSaledata
                    this.salePayType = data.data.companyInfo.coSale.salePayType
                    if(this.viewType == 'add' && this.coSale.delivery_id != undefined){
                        this.data.saleDeliveryTypeId = this.coSale.delivery_id
                        if(this.coSale.delivery_id == 4) this.selectDeliveryType(this.coSale.delivery_id)
                        if(this.coSale.pledge) this.data.pledge = true
                        if(this.coSale.makefirst) this.data.makefirst = true
                    }
                    this.saler = data.data.saler
                    if(this.saler.length == 1){
                        this.data.saler_id = this.saler[0].id
                    }
                }
            })
        },
        getCompanyInfo(id){
            $.ajax({
                url:'/admin/sale/searchCompany?request=detail',
                type:'post',
                data:{company_id:id},
                success:(data)=>{
                    data = JSON.parse(data)
                    this.companyInfo = data.data.companyInfo
                    
                }
            })
        },
        setPriority(num){
            this.data.priority = $("#priority-num").text();
        },
        // 按分类和关键字获取产品和产品角色信息
        searchPro(){
            this.proInfo = []
            $("#select_prochar_list option:selected").text('LOADING...')
            $.ajax({
                url:'/admin/sale/getProInfo',
                type:'post',
                data:{proCateId:this.proCateId,searchText:this.searchText},
                success:(data)=>{
                    data = JSON.parse(data)
                    if(data.data.length > 0){
                        this.proInfoKey = -1
                        $("#select_prochar_list option:selected").text('选择产品列表')
                        this.proInfo = data.data
                        if(data.data.length == 1){
                            this.proInfoKey = 0
                            this.proStoreStatus(this.proInfo[0]['pro_id'],this.proInfo[0]['prochar_id'],'status',this.proInfo[0]['prochar_qty']);
                            this.proStoreStatus(this.proInfo[0]['pro_id'],this.proInfo[0]['prochar_id'],'storeType',0);
                        } 
                    }else{
                        $("#select_prochar_list option:selected").text('暂无内容，完善搜索条件')
                    }
                }
            })
        },
        // 设置 是否包销 是否先配货，是否需要定金
        setSaleStatus(type){
            switch(type){
                case 'underwrite':
                    this.data.underwrite = !this.data.underwrite
                    break;
                case 'pledge':
                    this.data.pledge = !this.data.pledge
                    break;
                case 'makefirst':
                    this.data.makefirst = !this.data.makefirst
                    console.log(this.data.makefirst)
                    break;
            }
        },
        setSaleOrderRemarks(){
            $('#remark_Modal #orderRemarks').val('')
            this.getPublicInfo()
        },
        setSaleOrderRemarkData(){
            // $('#orderRemarksKey').val() == -1  为新增，其他未编辑
            if($('#orderRemarksKey').val() == -1){
                if(this.saleOrderRemarkData == undefined) this.saleOrderRemarkData = []
                this.saleOrderRemarkData.push({
                    viewid:this.saleOrderRemarkData.length+1,
                    content:$("#orderRemarks").val(),
                    private:this.orderRemarkprivate,
                    create_at:this.create_at,
                    create_name:this.create_name,
                    isset:false
                })
            }else{
                this.saleOrderRemarkData[$('#orderRemarksKey').val()]['content'] = $("#orderRemarks").val()
                $('#orderRemarksKey').val(-1)
            }
           
        },
        setOrderRemarkprivate(status){
            if(status){
                this.orderRemarkprivate = false
            }else{
                this.orderRemarkprivate = true
            }
        },
        // 设置产品数量input 上限max
        setProMax(){
            if ( $('#orderNum').val() > this.proStatus.storeType.storeQty && this.proStatus.storeType.storeQty > 0) $('#orderNum').val(this.proStatus.storeType.storeQty) 
        },
        // 获取产品最低价格
        proMaxPrice(){
            // this.point('','#alertMain','hide')
            if( $('#orderPrice').val() < this.proInfo[this.proInfoKey].lowest_price ){
                $('#orderPrice').val(this.proInfo[this.proInfoKey].lowest_price)
                // this.point('当前产品最低单价为：'+this.proInfo[this.proInfoKey].lowest_price,'#alertMain','show',4)
            } 
        },
        selectProInfoKey(){
            
            if( this.proInfo.length == 0 || $('#orderNum').val() <= 0 || $('#orderPrice').val() <= 0 ){
                var msg = ''
                if($('#orderPrice').val() <= 0) msg = '请选择正确的产品单价'
                if($('#orderNum').val() <= 0) msg = '请选择正确的产品数量'
                if(this.proInfo.length  <= 0 ) msg = '添加的产品不存在，请选择正确的产品'
                this.point(msg,'#alertMain','show')
                return false
            }
            if(this.proInfoKey == -1 ){
                this.point('请选择正确的产品','#alertMain','show')
                return false
            } 
            var lengthdata=this.proInfo[this.proInfoKey];
            lengthdata['orderNum']=$('#orderNum').val();
            lengthdata['orderPrice']= Number($('#orderPrice').val());
            lengthdata['Subtotal']=$('#orderNum').val() * $('#orderPrice').val();
            lengthdata['status'] = this.proStatus.status
            lengthdata['storeType'] = ''
            lengthdata['storeType_subWarehouseQty'] = this.proStatus.storeType.subWarehouseQty
            lengthdata['storeType_storeQty'] = this.proStatus.storeType.storeQty

            if( this.proStatus.status.status == 0 ){
                lengthdata['storeType'] = 'futures';
            }  
            // 订单qty 大于分仓库qty 小于所有仓库qty 则当前产品订单为外调状态
            if( ($('#orderNum').val() > this.proStatus.storeType.subWarehouseQty) && ($('#orderNum').val() < this.proStatus.storeType.storeQty)){
                lengthdata['storeType'] = 'outGet';
            } 
            lengthdata['isset'] = false
            console.log(lengthdata)
            
            var new_arr = this.orderList
            var length = new_arr.length

            var j = 1
            for(var i=0;i<length;i++) {
                if( new_arr[i]['pro_id'] == this.proInfo[this.proInfoKey]['pro_id'] && new_arr[i]['prochar_id'] == this.proInfo[this.proInfoKey]['prochar_id']){
                    this.point('当前添加的产品已存在','#alertMain','show')
                    return false
                    j = 1;
                }else{
                    j = 0
                }
            }

            if(length == 0 || j == 0 ){
                new_arr.push(lengthdata);
            }
            this.orderList = []
            this.orderList = new_arr
            this.orderListLength = this.orderList.length

            this.getProCount()
            this.point('','#alertMain','hide')
        },
        getProCount(type='add'){
            // 产品统计数据
            this.proCount.package_sum = 0
            this.proCount.m3 = 0
            this.proCount.kgs = 0
            this.proCount.price = 0

            for (var k = 0; k < this.orderList.length; k++) {
                if(this.orderList[k]['storeType'] != "futures"){
                    this.proCount.package_sum += (this.orderList[k]['orderNum']/this.orderList[k]['prochar_qty'])
                    this.proCount.package_sum = Math.round(this.proCount.package_sum*100)/100
                    this.proCount.m3 += (this.orderList[k]['orderNum']/this.orderList[k]['prochar_qty']*this.orderList[k]['ctn_m3'])
                    this.proCount.m3 = Math.round(this.proCount.m3*100)/100
                    this.proCount.kgs += (this.orderList[k]['orderNum']/this.orderList[k]['prochar_qty']*this.orderList[k]['ctn_kgs'])
                    this.proCount.kgs = Math.round(this.proCount.kgs*100)/100
                    this.proCount.price += this.orderList[k]['Subtotal']    
                }
                
            }
            this.billDate['price'] = this.proCount.price
        },
        // 获取销售记录
        getSaleRecording(){
            if(this.proInfoKey != -1){
                if($('#requestType').val() == 'add'){
                    var url = '/admin/sale/saleAdd?request=saleRecording'
                }else{
                    var url = '/admin/sale/saleEdit?request=saleRecording'
                }

                $.ajax({
                    url:url,
                    type:'post',
                    data:{pro_id:this.proInfo[this.proInfoKey]['pro_id'],prochar_id:this.proInfo[this.proInfoKey]['prochar_id'],company_id:this.data.companyId,co_branch_id:this.data.branchCompanyId},
                    success:(data)=>{
                        data = JSON.parse(data)
                        this.saleRecording = data
                        if(this.saleRecording.length > 0){
                            $("#pro_history").show()
                            $("#pro_nothing").hide()
                        }else{
                            $("#pro_history").hide()
                            $("#pro_nothing").show()
                        }
                    }
                })

                this.proStoreStatus(this.proInfo[this.proInfoKey]['pro_id'],this.proInfo[this.proInfoKey]['prochar_id'],'status',this.proInfo[this.proInfoKey]['prochar_qty']);
                // this.proStoreStatus(this.proInfo[this.proInfoKey]['pro_id'],this.proInfo[this.proInfoKey]['prochar_id'],'storeType',$('#orderNum').val());   
                this.proStoreStatus(this.proInfo[this.proInfoKey]['pro_id'],this.proInfo[this.proInfoKey]['prochar_id'],'storeType',0);
            }
            
        },
        proStoreStatus(pro_id,prochar_id,status,prochar_qty=0){

            if(status == 'status'){
                this.proStatus.status = {}
            }else{
                this.proStatus.storeType = {}
            }
            if($('#requestType').val() == 'add'){
                var url = '/admin/sale/saleAdd?request='+status
            }else{
                var url = '/admin/sale/saleEdit?request='+status
            }
            this.proStoreStatusData = ''
            $.ajax({
                url:url,
                type:'post',
                data:{pro_id:pro_id,prochar_id:prochar_id,prochar_qty:prochar_qty},
                // async:false,
                success:(data)=>{
                    data = JSON.parse(data)
                    if(status == 'status'){
                        this.proStatus.status = data
                    }else{
                       this.proStatus.storeType = data 
                    }
                }
            })
        },
        changeOrderNum(dataName,key,event,type){
            var data = this.orderList
            if(data[key].status.status != 0){

                this.orderList = []
                data[key][type] = event.target.value
                data[key]['Subtotal'] = 0
                if(type == 'orderNum'){

                    if(event.target.value > data[key]['storeType_storeQty'] ){
                        data[key]['qty'] = data[key]['storeType_storeQty']
                        data[key]['orderNum'] = data[key]['storeType_storeQty']
                    } else{
                        data[key]['qty'] = event.target.value
                    }
                    data[key]['Subtotal'] = data[key]['qty'] * data[key]['orderPrice']

                    if( data[key].status.status == 0 ){
                        data[key]['storeType'] = 'futures';
                    }  
                    // 订单qty 大于分仓库qty 小于所有仓库qty 则当前产品订单为外调状态
                    if( (data[key]['qty'] > data[key]['storeType_subWarehouseQty']) && (data[key]['qty'] <= data[key]['storeType_storeQty'])){
                        data[key]['storeType'] = 'outGet';
                    }

                }else{
                    if(event.target.value < data[key]['lowest_price']){
                        data[key]['orderPrice'] = data[key]['lowest_price']
                        event.target.value = data[key]['lowest_price']
                    } 
                    data[key]['Subtotal'] = event.target.value * data[key]['orderNum']
                }
                if(data[key]['discountType'] == '%'){
                    data[key]['orderListDiscountPriceSum'] = Math.round(data[key]['orderNum'] * data[key]['orderPrice']*(data[key]['orderListDiscount']/100))
            
                }else if(data[key]['discountType'] == undefined){
                    data[key]['orderListDiscountPriceSum'] = 0
                }else{
                    data[key]['orderListDiscountPriceSum'] = event.target.orderNum * data[key]['discount']
                }
                this.orderList = data
                this.getProCount()
            }
        },
        // 设置折扣
        proDiscount(key){
            this.orderListKey = key
            this.discountData = this.orderList[key];
        },
        setDiscount(){
            var ddata = this.discountData
            this.discountData = []
            ddata['discountType'] = $("input[name='discount_type']:checked").val() == 1 ? '%' : 'BRL'
            if(ddata['discountType'] == '%'){
                var inputDiscount = $('#discount').val() > 100 ? 100 : $('#discount').val();
            }else{
                var inputDiscount = $('#discount').val();
            }

            if(inputDiscount > ddata['lowest_discount']){
                ddata['discount'] = ddata['lowest_discount']
                this.point('当前产品最高折扣为：'+ddata['lowest_discount']+' '+ddata['discountType'],'#pro_discount_Modal .alert','show',4)
            }else{
                ddata['discount'] = inputDiscount
            }

            if(ddata['discountType'] == '%'){
                ddata['discountPriceSum'] = Math.round(ddata['orderPrice'] * (ddata['discount']/100) * ddata['orderNum']*100)/100 
            }else{
                ddata['discountPriceSum'] =  ddata['discount']
            }

            this.discountData = ddata
        },
        discountSave(){
            var olData = this.orderList
            this.orderList = []
            olData[this.orderListKey]['orderListDiscount'] = $('#discount').val()
            // 判断折扣方式 是百分比还是 数据 是百分比 就需要计算，不是 就只要获取值
            if($("input[name='discount_type']:checked").val()  == 1){
                olData[this.orderListKey]['orderListDiscountPrice'] = olData[this.orderListKey]['orderPrice'] *($('#discount').val()/100)
                olData[this.orderListKey]['orderListDiscountPriceSum'] = Math.round(olData[this.orderListKey]['orderPrice'] * ($('#discount').val()/100) * olData[this.orderListKey]['orderNum']*100)/100 
            }else{
                olData[this.orderListKey]['orderListDiscountPrice'] = $('#discount').val()
                olData[this.orderListKey]['orderListDiscountPriceSum'] = $('#discount').val()
            }
            
            olData[this.orderListKey]['discountType'] = $("input[name='discount_type']:checked").val()  == 1 ? '%' : 'BRL'
            this.orderList = olData
            this.setBillDate()
            $('#pro_discount_Modal').modal('toggle')
        },
        setBillDate(){
            this.billDate['discountPrice'] = 0
            this.billDate['commissionPrice'] = 0
            for (var i = 0; i < this.orderList.length; i++) {
                this.billDate['discountPrice'] += this.orderList[i]['discountPriceSum'] ? this.orderList[i]['discountPriceSum'] : 0
                this.billDate['commissionPrice'] += this.orderList[i]['commissionPrice'] ? this.orderList[i]['commissionPrice'] : 0
            }
        },
        // 设置提成
        proCommission(key){
            this.orderListKey = key
            this.commissionData = this.orderList[key];
        },
        setCommission(){
            var data = this.commissionData
            this.discountData = []
            data['commission'] = $('#commission').val()
            data['commissionPrice'] = Math.round(data['orderPrice'] * data['orderNum'] * ($('#commission').val()/100) * 100)/100 
            this.commissionData = data
            // this.billDate['commissionPrice'] += data['commissionPrice']
        },
        commissionSave(){
            var cData = this.orderList
            this.orderList = []
            cData[this.orderListKey]['orderListCommission'] = $('#commission').val()
            this.orderList = cData
            this.setBillDate()
            $('#pro_commission_Modal').modal('toggle')
        },
        // 设置备注
        proRemarks(key){
            this.private = false
            this.add = false
            this.rationed = false
            $('#pro_remark_Modal #remarksContent').val('')
            this.orderListKey = key
            this.remarksData = this.orderList[key];
            this.remarksData['key'] = key
            this.addRemarksData = this.orderList[key].remarksList 
        },
        addRemarks(){
            // 判断是编辑 还是 追加
            if($('#remarksContentkey').val() == -1){

                // 判断是否重复添加
                var j = 0;
                if(this.addRemarksData == undefined){
                    this.addRemarksData = []
                }else{
                    $.each(this.addRemarksData,function(key,value){  
                        if(value.content == $('#remarksContent').val()) j=1
                    });
                } 
                
                if(j==1){
                    this.point('内容已存在','#pro_remark_Modal .alert','show')
                }else{
                    this.addRemarksData.push({
                        viewid:this.addRemarksData.length+1,
                        content:$('#remarksContent').val(),
                        private:this.private,
                        add:this.add,
                        rationed:this.rationed,
                        create_name:this.create_name,
                        create_at:this.create_at,
                        isset:false,
                    })   
                    this.point('','#pro_remark_Modal .alert','hide')
                }
                
            }else{
                this.addRemarksData[$('#remarksContentkey').val()]['content'] = $('#remarksContent').val()
                this.addRemarksData[$('#remarksContentkey').val()]['private'] = this.private
                this.addRemarksData[$('#remarksContentkey').val()]['add'] = this.add
                this.addRemarksData[$('#remarksContentkey').val()]['rationed'] = this.rationed
                $('#remarksContentkey').val(-1)
                this.point('','#pro_remark_Modal .alert','hide')
            }
            // this.addRemarksData = data
        },
        saveProListRemarks(key){
            var j = 0;
            $.each(this.orderList[key],function(key,value){  
                if(key == 'remarksList') j=1
            });
            if(j!=1) this.orderList[key]['remarksList'] = []
            // 绑定每组销售订单产品的备注信息
            this.orderList[key]['remarksList'] = this.addRemarksData
        },
        setbillDateCostPrice(){
            console.log(this.costData)
            this.billDate['costPrice'] = 0
            $.each(this.costData, (key, value) => {

                if(value.options == '-'){
                    this.billDate['costPrice'] -=  Number(value.costPrice)
                } else if(value.options == '+'){
                    this.billDate['costPrice'] +=  Number(value.costPrice)
                } 
            });
        },
        // 设置费用
        setCost(){
            if($('#costPrice').val() > 0){
                if($('#costPriceKey').val() == -1){
                    // 判断是否重复添加
                    var j = 0;
                    if(this.costData == undefined){
                        this.costData = []
                    }else{
                        $.each(this.costData, (key, value) => {
                            if((value.costPrice == $('#costPrice').val()) && (value.saleCostTypeId == this.saleCostType[$('#saleCostTypeIndex').val()].id)) j=1
                        });
                    } 
                    
                    if(j==1){
                        this.point('费用类型为：'+this.saleCostType[$('#saleCostTypeIndex').val()].name+',价格为：'+$('#costPrice').val()+' 已存在','#main .alert','show')
                    }else{

                        this.costData.push({
                            viewid:this.costData.length+1,
                            content:this.saleCostType[$('#saleCostTypeIndex').val()].name,
                            saleCostTypeId:this.saleCostType[$('#saleCostTypeIndex').val()].id,
                            options:this.saleCostType[$('#saleCostTypeIndex').val()].options,
                            costRemarks:$('#costRemarks').val(),
                            costPrice:$('#costPrice').val(),
                            create_name:this.create_name,
                            create_at:this.create_at,
                            del_at:0,
                            isset:false
                        })
                        this.costDataLength = this.costData.length
                        this.setbillDateCostPrice()
                        this.point('','#main .alert','hide')
                    }
                }else{
                    this.costData[$('#costPriceKey').val()]['content'] = this.saleCostType[$('#saleCostTypeIndex').val()].name
                    this.costData[$('#costPriceKey').val()]['saleCostTypeId'] = this.saleCostType[$('#saleCostTypeIndex').val()].id
                    this.costData[$('#costPriceKey').val()]['options'] = this.saleCostType[$('#saleCostTypeIndex').val()].options
                    this.costData[$('#costPriceKey').val()]['costRemarks'] = $('#costRemarks').val()
                    this.costData[$('#costPriceKey').val()]['costPrice'] = $('#costPrice').val()
                    $('#costPriceKey').val(-1)
                    this.point('','#main .alert','hide')
                    this.setbillDateCostPrice()
                }
                this.setPaymentPrice_()
            }else{
                this.point('金额不能为零','#main .alert','show')
            }
            
        },
        // 计算this.billDate['paymentPrice']
        setPaymentPrice(thisDayTime=''){
            if(!thisDayTime) this.dayTime = this.create_at
            this.billDate['paymentPrice'] = 0
            for (var i = 0; i < this.paymentList.length; i++) {
                this.billDate['paymentPrice'] += Number( this.paymentList[i]['paymentAmount'] )
            }
            this.getInvoiceType()
            if($('#paymentAmountKey').val() < 0 ) this.setPaymentPrice_()
            
        },
        // 付款安排 设置默认值
        setPaymentPrice_(){
            var price = this.billDate.price - this.billDate.discountPrice + this.billDate.costPrice

            var price_ = 0
            var paymentPercentage = 100
            var paymentPercentage_ = 0
            for (var i = 0; i < this.paymentList.length; i++) {
                price_ += Number( this.paymentList[i]['paymentAmount'])
                paymentPercentage_ += Number( this.paymentList[i]['paymentPercentage'])
            }
            var aa = Number(price*100)
            var bb = Math.floor(price_*100)

            $('#paymentAmount').val( (aa-bb)/100)

            $('#paymentPercentage').val( Math.floor((aa-bb)/100/price*100*10)/10 )
        },
        paymentCalculation(type){
            var price = 0;
            for (var i = 0; i < this.paymentList.length; i++) {
                if($('#paymentAmountKey').val() != i){
                    price += Number(this.paymentList[i]['paymentAmount'])
                }
            }
            price = Math.floor(price*100)/100
            var priceShiff = this.billDate.price - this.billDate.discountPrice + this.billDate.costPrice - price
            if(type == '%'){
                if($('#paymentPercentage').val() > 100) $('#paymentPercentage').val(100)
                if(priceShiff == 0) $('#paymentPercentage').val(0)
                var num = priceShiff * ($('#paymentPercentage').val()/100)
                $('#paymentAmount').val( num )
            }else if(type == 'BRL'){
                if($('#paymentAmount').val() > priceShiff ) $('#paymentAmount').val(priceShiff)

                // $('#paymentPercentage').val(  Math.round(($('#paymentAmount').val()/priceShiff)*100)*100/100 )
                $('#paymentPercentage').val( priceShiff==0 ? 0 : ($('#paymentAmount').val()/priceShiff*100).toFixed(2) ) 

            }
        },
        // 付款安排
        setPayment(){

            if(this.salePayType[$('#salePayType').val()] == undefined){
                this.point('请选择付款方式','#main .alert','show')
                return false
            }

            if($('#paymentAmount').val() <= 0){
                this.point('付款安排金额不能小于等于0','#main .alert','show')
                return false
            }

            if($('#paymentAmountKey').val() == -1){

                // 判断是否重复添加
                var j = 0;
                if(this.paymentList == undefined){
                    this.paymentList = []
                }else{
                } 
                    if(this.salePayType[$('#salePayType').val()].id == 6) this.salePayBill = 1;
                    this.paymentList.push({
                        viewid:this.paymentList.length+1,
                        content:this.salePayType[$('#salePayType').val()].content,
                        paytype_id:this.salePayType[$('#salePayType').val()].id,
                        create_at:this.create_at,
                        create_name:this.create_name,
                        paymentDay:$('#paydate').val().split(' ')[0],
                        paymentAmount:$('#paymentAmount').val(),
                        paymentPercentage:$('#paymentPercentage').val(),
                        paymentPayDay:$('#paymentPayDay').val(),    // 付款天数
                        isset:false,
                        account_id:this.data.receivingAccounId,
                        invoiceTypeId:this.data.invoiceTypeId,
                        haspayery:0
                    })
                    // this.paymentList = data
                    this.setPaymentPrice()
                    this.point('','#main .alert','hide')
                    
                // }
            }else{
                this.paymentList[$('#paymentAmountKey').val()]['paymentDay'] = $('#paydate').val().split(' ')[0]
                this.paymentList[$('#paymentAmountKey').val()]['paymentAmount'] = $('#paymentAmount').val()
                this.paymentList[$('#paymentAmountKey').val()]['paymentPercentage'] = $('#paymentPercentage').val()
                this.paymentList[$('#paymentAmountKey').val()]['paymentPayDay'] = $('#paymentPayDay').val()
                this.paymentList[$('#paymentAmountKey').val()]['paytype_id'] = this.salePayType[$('#salePayType').val()].id
                this.paymentList[$('#paymentAmountKey').val()]['content'] = this.salePayType[$('#salePayType').val()].content
                this.paymentList[$('#paymentAmountKey').val()]['haspayery'] = 0
                $('#paymentAmountKey').val(-1)
                this.point('','#main .alert','hide')
                this.setPaymentPrice()
            }
            this.setPaymentPrice_()
        },
        // 指定收款账号是否显示
        isHideReceivingAccounId(){
            // if(this.salePayType[$('#salePayType').val()].id == 6){
            //     $('.receivingAccountItem').show();
            // }else{
            //     $('.receivingAccountItem').hide();
            // }
        },
        clickSetPayment(key){
            var data = this.paymentList
            var price = 0;
            var paymentPercentage = 0
            for (var i = 0; i < this.paymentList.length; i++) {
                price += Number(this.paymentList[i]['paymentAmount'])
                paymentPercentage += Number(this.paymentList[i]['paymentPercentage'])
            }
            // 获取剩余未安排金额
            var priceShiff = this.billDate.price - this.billDate.discountPrice + this.billDate.costPrice - price
            if(priceShiff > 0){
                for (var i = 0; i < this.quickInput[key].data.length; i++) {
                    var payDay = this.quickInput[key].data[i].day > 0 ? this.payDayCalculate(this.quickInput[key].data[i].day) : this.create_at
                    data.push({
                        viewid:data.length+1,
                        content:this.quickInput[key].name,
                        paytype_id:this.quickInput[key].id,
                        create_at:this.create_at,
                        create_name:this.create_name,
                        paymentDay:payDay,
                        paymentAmount:priceShiff*this.quickInput[key].data[i].percentage/100,
                        paymentPercentage:this.quickInput[key].data[i].percentage-paymentPercentage,
                        paymentPayDay:this.quickInput[key].data[i].day,
                        isset:false,
                    })
                }
                this.paymentList = data
            }
        },
        setPayDate(){
            console.log($(this).val())
        },
        jumpPaymentRemarksData(key){
            $('#paymentRemarksContent').val('')
            this.getPublicInfo()
            this.publicInfo['paymentName'] = this.paymentList[key]['content']
            this.publicInfo['paymentId'] = this.paymentList[key]['id']
            this.publicInfo['paymentCreate_at'] = this.paydate
            this.publicInfo['paymentAmount'] = this.paymentList[key]['paymentAmount']
            this.publicInfo['key'] = key
            this.paymentRemarksDataList = this.paymentList[key]['remarksList']
        },
        setpaymentRemarksList(){
            if($('#paymentRemarksContentKey').val() == -1){
                if(this.paymentRemarksDataList == undefined) this.paymentRemarksDataList = []
                this.paymentRemarksDataList.push({
                    content:$('#paymentRemarksContent').val(),
                    create_at:this.create_at,
                    create_name:this.create_name,
                    isset:false,
                })    
            }else{
                this.paymentRemarksDataList[$('#paymentRemarksContentKey').val()]['content'] = $('#paymentRemarksContent').val()
                $('#paymentRemarksContentKey').val(-1)
            }
            
        },
        savePaymentRemarks(key){
            var j = 0;
            $.each(this.paymentList[key],function(key,value){  
                if(key == 'remarksList') j=1
            });
            if(j!=1) this.paymentList[key]['remarksList'] = []
            // 绑定没个付款安排的备注信息
            this.paymentList[key]['remarksList'] = this.paymentRemarksDataList
        },
        // 点击付款登记nav-tab 计算金额
        setPayreyHeadTable()
        {   
            if(this.salePayreg == undefined) this.salePayreg = []
            this.salePayreg = this.paymentList
            this.billDate['payregPaid'] = 0   // 付款登记到账合计金额（已付）
            this.billDate['overdraft'] = 0   // 付款登记到账合计金额（已付）
            for (var i = 0; i < this.payregList.length; i++) {
                this.billDate['payregPaid'] += Number( this.payregList[i]['paid'] )
                this.billDate['overdraft'] += (Number( this.payregList[i]['amount']) - Number( this.payregList[i]['paid']))
            }
        },
        // 登记弹框显示类型
        payperyViewShow(paytype_id,type=''){
            $('#payreg_transfer'+type).css('display','none');
            $('#payreg_cheque'+type).css('display','none');
            $('#payreg_cash'+type).css('display','none');
            $('#payreg_voucher'+type).css('display','none');

            if(paytype_id == 3 || paytype_id == 4){
                $('#payreg_cheque'+type).css('display','block');
                if(!type) $('#chequeDay').val(this.publicInfo.paymentDay)
            } 
            if(paytype_id == 2){
                $('#payreg_voucher'+type).css('display','block');
            }
            if(paytype_id == 1){
                $('#payreg_cash'+type).css('display','block');
                if(!type) $('#payregCashPayDay').text(this.publicInfo.paymentDay)

            }
            if(paytype_id == 5){
                $('#payreg_transfer'+type).css('display','block');
                if(!type) $('#transferDay').val(this.publicInfo.paymentDay)
            } 
            if(this.fastPayrey_) this.fastPayrey_paytype_id = paytype_id
        },
        // 付款登记
        clickSalePayreg(key,dataName){
            this.payeryInputNull()
            this.voucherData = []
            this.PayeryChequeData = []
            this.payerytransferData = []
            this.savePayeryPaytype_id = 0;
            this.payregEdit = false;
            this.payeryIsEdit = -1;
            this.point('','#payreg_Modal .alert','hide')

            this.getPublicInfo()
            console.log(this[dataName][key])
            this.publicInfo['paymentName'] = dataName == 'salePayreg' ? this[dataName][key]['content'] : this[dataName][key]['paytype_name']
            this.publicInfo['paymentDay'] = dataName == 'salePayreg' ? this[dataName][key]['paymentDay'] : this[dataName][key]['pay_day']
            this.publicInfo['paymentId'] = dataName == 'salePayreg' ? this[dataName][key]['id'] : this[dataName][key]['sale_payplan_id']
            this.publicInfo['paymentAmount'] = dataName == 'salePayreg' ? this[dataName][key]['paymentAmount'] : this[dataName][key]['amount']
            this.publicInfo['paytype_id'] = this[dataName][key]['paytype_id']
            this.publicInfo['key'] = key

            this.payperyViewShow(this.publicInfo['paytype_id'])
            // 删除未保存到登记table list（payregList） 的数据 
            if(this[dataName][key]['payregDetail']){
                for (var i = 0; i < this[dataName][key]['payregDetail'].length; i++) {
                    if(this[dataName][key]['payregDetail'][i]['isset'] == 2){
                        this[dataName][key]['payregDetail'].splice(i,1);
                    }
                }
            }
            // 判断是否编辑
            if(dataName == 'payregList'){
                if(this[dataName][key]['paytype_id'] == 2){
                    this.voucherData = this[dataName][key]['payregDetail']
                    this.voucherPriceSum[key] = this[dataName][key]['payregDetail'][0]['amount'] == undefined ? 0 : this[dataName][key]['payregDetail'][0]['amount']
                } 
                if(this[dataName][key]['paytype_id'] == 3 || this[dataName][key]['paytype_id'] == 4) {
                    this.PayeryChequeData = this[dataName][key]['payregDetail']
                    // this.payregChequeInfo.chequeBankValue = this[dataName][key].payregDetail[0]['bank_key']
                    if(this[dataName][key].payregDetail[0]['bank_key']){
                        $('#chequeBank').val(this[dataName][key].payregDetail[0]['bank_key'])
                    }else{
                        this.getBank()
                        $.each(this.bankList, (keybankList, value) => {
                            if(value.id == this[dataName][key]['payregDetail'][0]['bank_id']){
                                $('#chequeBank').val(keybankList)
                            } 
                        });
                    }
                    
                    this.chequePriceSum[key] = 0
                    this.chequePriceSum[key] = this[dataName][key]['payregDetail'][0]['amount'] == undefined ? 0 : this[dataName][key]['payregDetail'][0]['amount']
                }
                if(this[dataName][key]['paytype_id'] == 5){
                    this.payerytransferData = this[dataName][key]['payregDetail']
                    this.transferPriceSum[key] = this[dataName][key]['payregDetail'][0]['amount'] == undefined ? 0 : this[dataName][key]['payregDetail'][0]['amount']
                } 
                this.publicInfo['title'] = '编辑'

                this.modalEditAndDel(key,'edit','payregList')
            } else{
                if(this[dataName][key]['paytype_id'] == 5)
                    this.payregChequeInfo.payreg_transfer_pay_dayValue = this.publicInfo['paymentDay']
                    this.payregChequeInfo.transferPriceValue = this.publicInfo['paymentAmount']
                if(this[dataName][key]['paytype_id'] == 3 || this[dataName][key]['paytype_id'] == 4)
                    this.payregChequeInfo.chequeDay = this.publicInfo['paymentDay']
                    this.payregChequeInfo.chequePrice = this.publicInfo['paymentAmount']
                this.publicInfo['title'] = '快捷付款登记'
            }
            // 代金券info
            this.getVoucher()
            this.getBank()
            this.getCoBank()
        },
        fastPayrey(key,dataName){
            this.fastPayrey_ = true
            this.removeClassActive('#payreg_down_Modal',this[dataName][key]['paytype_id'])
            this.payperyViewShow(this[dataName][key]['paytype_id'],'_')
            this.voucherData_ = []
            this.PayeryChequeData_ = []
            this.payerytransferData_ = []

            this.payregAmount_ = this[dataName][key]['paymentAmount']
            $('#chequePrice_').val(this[dataName][key]['paymentAmount'])
            $('#transferPrice_').val(this[dataName][key]['paymentAmount'])
        },
        clickUseVoucher(key){
            this.savePayeryPaytype_id = 2;
            if(key >= 0){
                var classText = '#payreg_Modal .alert'

            }else{
                var classText = '#payreg_down_Modal .alert'
            } 
            if($('#voucher').val() >= 0 || $('#voucher_').val() >= 0){
                this.point(msg,classText,'hide')
                // 计算当前需要登记的 代金券合计
                if(this.voucherPriceSum[key] == undefined) this.voucherPriceSum[key] = 0
                if(key >= 0){
                    if(this.voucherData == undefined) this.voucherData = []
                    this.voucherData.push({
                        id:this.voucherList[$('#voucher').val()].id,
                        amount:this.voucherList[$('#voucher').val()].amount,
                        valid_time:this.voucherList[$('#voucher').val()].valid_time,
                        valid_day:this.voucherList[$('#voucher').val()].valid_day,
                        isSave:2,
                        del_at:0,
                    })    
                    this.voucherPriceSum[key] += this.voucherList[$('#voucher').val()].amount   
                }else{
                    if(this.voucherData_ == undefined) this.voucherData_ = []
                    this.voucherData_.push({
                        id:this.voucherList[$('#voucher_').val()].id,
                        amount:this.voucherList[$('#voucher_').val()].amount,
                        valid_time:this.voucherList[$('#voucher_').val()].valid_time,
                        valid_day:this.voucherList[$('#voucher_').val()].valid_day,
                        isSave:2,
                        del_at:0,
                    }) 
                    this.voucherPriceSum[key] += this.voucherList[$('#voucher_').val()].amount   
                }
                 
            }else{
                var msg = '请选择正确的代金券';
                this.point(msg,classText,'show')
            }

        },
        setChequeDay(key){
            this.savePayeryPaytype_id=3
            if(key >= 0){
                var classText = '#payreg_Modal .alert'
            }else{
                var classText = '#payreg_down_Modal .alert'
            } 
            this.point(msg,classText,'hide')
            if(this.chequePriceSum[key] == undefined) this.chequePriceSum[key] = 0
            if(key >= 0){
                if($('#chequeBank').val() >=0 && $('#chequeNo').val() && $('#chequeSignature').val() && $('#chequePrice').val()){
                    if(this.payregChequeInfo.chequeNoKey == -1 && $('#chequeNoEditKey').val() == -1 ){
                        var j = 0
                        $.each(this.PayeryChequeData, (key1, value) => {
                            if(value.chequeNo == $('#chequeNo').val()) j=1
                        });

                        if(j==1){
                            this.point('票号：'+$('#chequeNo').val()+' 已存在',classText,'show')
                        }else{
                            if(this.PayeryChequeData == undefined) this.PayeryChequeData = []
                            this.PayeryChequeData.push({
                                viewid:this.PayeryChequeData.length+1,
                                bank_id:this.bankList[$('#chequeBank').val()].id,
                                bank_name:this.bankList[$('#chequeBank').val()].name,
                                bank_key:$('#chequeBank').val(),
                                chequeNo:$('#chequeNo').val(),
                                chequeSignature:$('#chequeSignature').val(),
                                chequePrice:$('#chequePrice').val(),
                                amount:$('#chequePrice').val(),
                                chequeDay:$('#chequeDay').val(),
                                chequeScan_url:$('#chequeScan_url').val(),
                                isSave:2,
                                del_at:0,
                            }) 
                        }
                        
                        this.savePayeryPaytype_id = 3;
                        this.chequePriceSum[key] += Number($('#chequePrice').val())   
                    }else{
                        var key_ = $('#chequeNoEditKey').val() > 0 ? $('#chequeNoEditKey').val() : 0
                        this.PayeryChequeData[key_]['bank_id'] = this.bankList[$('#chequeBank').val()].id
                        this.PayeryChequeData[key_]['bank_name'] = this.bankList[$('#chequeBank').val()].name
                        this.PayeryChequeData[key_]['bank_key'] = $('#chequeBank').val()
                        this.PayeryChequeData[key_]['chequeNo'] = $('#chequeNo').val()
                        this.PayeryChequeData[key_]['chequeSignature'] = $('#chequeSignature').val()
                        this.PayeryChequeData[key_]['chequePrice'] = $('#chequePrice').val()
                        this.PayeryChequeData[key_]['amount'] = $('#chequePrice').val()
                        this.PayeryChequeData[key_]['chequeDay'] = $('#chequeDay').val()
                        this.PayeryChequeData[key_]['chequeScan_url'] = $('#chequeScan_url').val()

                        this.chequePriceSum[key] += (Number($('#chequePrice').val()) - this.PayeryChequeData[key_]['chequePrice'])  
                        this.payeryIsEdit = this.payregChequeInfo.chequeNoKey;
                        this.payregChequeInfo.chequeNoKey = -1
                        $('#chequeNoEditKey').val(-1)
                    }
                        
                }else{
                    if($('#chequeBank').val() < 0) var msg = '请选择支票所在银行'
                    if(!$('#chequeNo').val()) var msg = '请输入正确的票号'
                    if(!$('#chequeSignature').val()) var msg = '请输入正确的署名'
                    if(!$('#chequePrice').val()) var msg = '请输入正确的价格'
                    // if(!$('#chequeDay').val()) var msg = '请选择正确的投递日期'
                    this.point(msg,classText,'show')
                }

            }else{
                if($('#chequeBank_').val() >=0 && $('#chequeNo_').val() && $('#chequeSignature_').val() && $('#chequePrice_').val()){
                if(this.PayeryChequeData_ == undefined) this.PayeryChequeData_ = []

                    if($('#chequeNoEditKey_').val() >= 0 ){
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].bank_id = this.bankList[$('#chequeBank_').val()].id
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].bank_name = this.bankList[$('#chequeBank_').val()].name
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].bank_key = $('#chequeBank_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].chequeNo = $('#chequeNo_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].chequeSignature = $('#chequeSignature_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].chequePrice = $('#chequePrice_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].amount = $('#chequePrice_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].chequeDay = $('#chequeDay_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].chequeScan_url = $('#chequeScan_url_').val()
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].isSave = 2
                        this.PayeryChequeData_[$('#chequeNoEditKey_').val()].del_at = 0
                        $('#chequeNoEditKey_').val(-1)
                    }else{
                        this.PayeryChequeData_.push({
                            viewid:this.PayeryChequeData_.length+1,
                            bank_id:this.bankList[$('#chequeBank_').val()].id,
                            bank_name:this.bankList[$('#chequeBank_').val()].name,
                            bank_key:$('#chequeBank_').val(),
                            chequeNo:$('#chequeNo_').val(),
                            chequeSignature:$('#chequeSignature_').val(),
                            chequePrice:$('#chequePrice_').val(),
                            amount:$('#chequePrice_').val(),
                            chequeDay:$('#chequeDay_').val(),
                            chequeScan_url:$('#chequeScan_url_').val(),
                            isSave:2,
                            del_at:0,
                        })
                        this.chequePriceSum[key] += Number($('#chequePrice_').val())
                    }
                }else{
                    if($('#chequeBank_').val() < 0) var msg = '请选择支票所在银行'
                    if(!$('#chequeNo_').val()) var msg = '请输入正确的票号'
                    if(!$('#chequeSignature_').val()) var msg = '请输入正确的署名'
                    if(!$('#chequePrice_').val()) var msg = '请输入正确的价格'
                    // if(!$('#chequeDay').val()) var msg = '请选择正确的投递日期'
                    this.point(msg,classText,'show')
                }
            }
        },
        setTransferData(key){
            this.savePayeryPaytype_id = 5;
            this.transferPriceSum[key] = 0
            if(key >= 0){
                var classText = '#payreg_Modal .alert'
            }else{
                var classText = '#payreg_down_Modal .alert'
            } 
            this.point(msg,classText,'hide')
            if(this.transferPriceSum[key] == undefined) this.transferPriceSum[key] = 0
            if(key >= 0){
                if( $('#transferInId').val() >= 0 && $('#transferNo').val() && $('#transferPrice').val() && $('#transferDay').val()){
                        
                    if(this.payregChequeInfo.transferKey == -1 && $('#transfereditKey').val() == -1){
                        if(this.payerytransferData == undefined) this.payerytransferData = []
                        var j = 0
                        $.each(this.payerytransferData, (key1, value) => {
                            if(value.transferNo == $('#transferNo').val()) j=1
                        });

                        if(j==1){
                            this.point('流水号：'+$('#transferNo').val()+' 已存在',classText,'show')
                        }else{
                            
                            this.payerytransferData.push({
                                viewid:this.payerytransferData.length,
                                transferOutId:$('#transferOutId').val() >= 0 ? this.co_bank[$('#transferOutId').val()].id : 0,
                                transferOutName:$('#transferOutId').val() >= 0 ? this.co_bank[$('#transferOutId').val()].bankname : '',

                                transferOutKey:$('#transferOutId').val(),
                                transferInKey:$('#transferInId').val(),

                                transferInId:this.receivingAccount[$('#transferInId').val()].id,
                                transferInName:this.receivingAccount[$('#transferInId').val()].accoun,

                                transferNo:$('#transferNo').val(),
                                transferPrice:$('#transferPrice').val(),
                                transferDay:$('#transferDay').val(),
                                transferscan_url:$('#transferscan_url').val(),     
                                isSave:2,  
                                del_at:0,
                            })
                            this.point('',classText,'hide')
                        }

                        this.transferPriceSum[key] += Number($('#transferPrice').val())
                    }else{

                        var key_ = $('#transfereditKey').val() > 0 ? $('#transfereditKey').val() : 0
                        this.transferPriceSum[key] += (Number($('#transferPrice').val()) - this.payerytransferData[0]['transferPrice'])
                        this.payerytransferData[key_]['transferOutId'] = $('#transferOutId').val() > 0 ? this.co_bank[$('#transferOutId').val()].id : 0
                        this.payerytransferData[key_]['transferOutName'] = $('#transferOutId').val() > 0 ? this.co_bank[$('#transferOutId').val()].bankname : ''
                        this.payerytransferData[key_]['transferOutKey'] = $('#transferOutId').val(),
                        this.payerytransferData[key_]['transferInKey'] = $('#transferInId').val(),
                        this.payerytransferData[key_]['transferInId'] = this.receivingAccount[$('#transferInId').val()].id
                        this.payerytransferData[key_]['transferInName'] = this.receivingAccount[$('#transferInId').val()].accoun
                        this.payerytransferData[key_]['transferNo'] = $('#transferNo').val()
                        this.payerytransferData[key_]['transferPrice'] = $('#transferPrice').val()
                        this.payerytransferData[key_]['amount'] = $('#transferPrice').val()
                        this.payerytransferData[key_]['transferDay'] = $('#transferDay').val()
                        this.payerytransferData[key_]['transferscan_url'] = $('#transferscan_url').val()
                        this.payeryIsEdit = this.payregChequeInfo.transferKey
                        $('#transfereditKey').val(-1)
                    }
                        
                }else{
                    var msg = '';
                    if($('#transferInId').val() < 0) msg = '请选择存入银行账号';
                    if(!$('#transferNo').val()) msg = '请输入正确的流水号';
                    if(!$('#transferPrice').val()) msg = '请输入正确金额';

                    this.point(msg,classText,'show')
                }
            }else{
                if($('#transferInId_').val() >= 0 && $('#transferNo_').val() && $('#transferPrice_').val() && $('#transferDay_').val()){
                    if($('#transfereditKey_').val() >= 0 ){
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferOutId'] = $('#transferOutId_').val() >= 0 ? this.co_bank[$('#transferOutId_').val()].id : 0
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferOutName'] = $('#transferOutId_').val() >= 0 ? this.co_bank[$('#transferOutId_').val()].bankname : ''
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferOutKey'] = $('#transferOutId_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferInKey'] = $('#transferInId_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferInId'] = this.receivingAccount[$('#transferInId_').val()].id
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferInName'] = this.receivingAccount[$('#transferInId_').val()].accoun

                        this.payerytransferData_[$('#transfereditKey_').val()]['transferNo'] = $('#transferNo_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferPrice'] = $('#transferPrice_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['amount'] = $('#transferPrice_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['transferDay'] = $('#transferDay_').val()
                        this.payerytransferData_[$('#transfereditKey_').val()]['scan_url'] = $('#scan_url_').val()    
                        this.payerytransferData_[$('#transfereditKey_').val()]['isSave'] = 2
                        this.payerytransferData_[$('#transfereditKey_').val()]['del_at'] = 0
                        $('#transfereditKey_').val(-1)
                    }else{
                        if(this.payerytransferData_ == undefined) this.payerytransferData_ = []
                        this.payerytransferData_.push({
                            viewid:this.payerytransferData_.length,
                            transferOutId:this.co_bank.length > 0 ? this.co_bank[$('#transferOutId_').val()].id : 0,
                            transferOutName:this.co_bank.length > 0 ? this.co_bank[$('#transferOutId_').val()].bankname : '',
                            transferOutKey:$('#transferOutId_').val(),
                            transferInKey:$('#transferInId_').val(),
                            transferInId:this.receivingAccount[$('#transferInId_').val()].id,
                            transferInName:this.receivingAccount[$('#transferInId_').val()].accoun,

                            transferNo:$('#transferNo_').val(),
                            transferPrice:$('#transferPrice_').val(),
                            amount:$('#transferPrice_').val(),
                            transferDay:$('#transferDay_').val(),
                            scan_url:$('#scan_url_').val(),     
                            isSave:2,
                            del_at:0,  
                        })
                        this.transferPriceSum[key] += Number($('#transferPrice_').val())
                    }

                }else{
                    var msg = '';
                    if($('#transferInId_').val() < 0) msg = '请选择存入银行账号';
                    if(!$('#transferNo_').val()) msg = '请输入正确的流水号';
                    if(!$('#transferPrice_').val()) msg = '请输入正确金额';

                    this.point(msg,classText,'show')
                }
            }  

        },
        payeryUpdate(){
            if(this.savePayeryPaytype_id == 3 || this.savePayeryPaytype_id == 4){
                this.payregList[this.payeryIsEdit]['amount'] = this.PayeryChequeData[0]['amount']
                this.payregList[this.payeryIsEdit]['pay_day'] = this.PayeryChequeData[0]['chequeDay']
                this.payregList[this.payeryIsEdit]['payregDetail'] = this.PayeryChequeData

                this.payregList[this.payeryIsEdit]['paytype_name'] = '现金支票'
                this.payregList[this.payeryIsEdit]['paytype_id'] = 3
            }else if(this.savePayeryPaytype_id == 5 ){
                this.payregList[this.payeryIsEdit]['amount'] = this.payerytransferData[0]['transferPrice'] 
                this.payregList[this.payeryIsEdit]['pay_day'] = this.payerytransferData[0]['transferDay']
                this.payregList[this.payeryIsEdit]['payregDetail'] = this.payerytransferData

                this.payregList[this.payeryIsEdit]['paytype_name'] = '转账'
                this.payregList[this.payeryIsEdit]['paytype_id'] = 5
            }else if(this.savePayeryPaytype_id == 2 ){
                this.payregList[this.payeryIsEdit]['amount'] = this.voucherData[0].amount
                this.payregList[this.payeryIsEdit]['paytype_name'] = '代金券'
                this.payregList[this.payeryIsEdit]['paytype_id'] = 2
                this.payregList[this.payeryIsEdit]['pay_day'] = this.voucherData[0].valid_time 
                this.payregList[this.payeryIsEdit]['payregDetail'] = this.voucherData
            }else{
                this.payregList[this.payeryIsEdit]['amount'] = $('#payregAmount').val()
                this.payregList[this.payeryIsEdit]['paytype_name'] = '现金'
                this.payregList[this.payeryIsEdit]['paytype_id'] = 1
                this.payregList[this.payeryIsEdit]['payregDetail'] = []
            }

        },
        savePayery(key){
            if(this.payeryIsEdit >= 0){
                this.payeryUpdate()
            }else{
                var j =0
                $.each(this.salePayreg[key],function(key,value){  
                    if(key == 'payregDetail') j=1
                });
                if(j==0){
                    this.salePayreg[key]['payregDetail'] = []
                } 

                if(this.payregList == undefined) {
                    this.payregList = new Array();
                }

                var paid = 0
                if(this.salePayreg[key].paytype_id == 1){   //  现金
                    if($('#payregAmount').val() > 0){
                        amount = $('#payregAmount').val()
                        paid = $('#payregAmount').val()
                        var paytype_name = '现金'
                        var pay_day = this.create_at
                    }else{
                        if(key >= 0){
                            var classText = '#payreg_Modal .alert'
                        }else{
                            var classText = '#payreg_down_Modal .alert'
                        } 
                        this.point(msg,classText)
                    }
                    

                }else if(this.salePayreg[key].paytype_id == 2){   //  代金券
                    var paytype_name = '代金券'
                    paid = this.voucherPriceSum[key]
                    var payregDetail = this.voucherData
                    // var pay_day = this.create_at

                }else if(this.salePayreg[key].paytype_id == 3 || this.salePayreg[key].paytype_id == 4){ // 支票/期票
                    var paytype_name = this.salePayreg[key].paytype_id == 3 ? '支票' : '期票'
                    var payregDetail = this.PayeryChequeData

                }else if(this.salePayreg[key].paytype_id == 5){ //转账
                    var paytype_name = '转账'
                    var payregDetail = this.payerytransferData
                }

                if(payregDetail){
                    for (var i = 0; i < payregDetail.length; i++) {
                        payregDetail[i]['isSave'] = 1
                    }
                }
                if(this.salePayreg[key].paytype_id != 1){
                    this.salePayreg[key]['payregDetail'] = payregDetail
                }
                
                    if(payregDetail != undefined){  
                        for (var i = 0; i < payregDetail.length; i++) {
                            var day = ''
                            var amount = payregDetail[i].amount
                            if(this.salePayreg[key].paytype_id == 2){
                                day = this.create_at
                            }else if(this.salePayreg[key].paytype_id == 3 || this.salePayreg[key].paytype_id == 4){
                                day = payregDetail[i]['chequeDay']
                            }else if(this.salePayreg[key].paytype_id == 5){
                                day = payregDetail[i]['transferDay']
                                amount = payregDetail[i].transferPrice
                            }
                            this.payregList.push({
                                viewid:this.payregList.length+1,
                                sale_id:this.data.saleOrderNo,
                                co_id:this.data.companyId,
                                paytype_id:this.salePayreg[key].paytype_id,
                                sale_payplan_id:this.salePayreg[key].id,
                                // pay_day:pay_day,
                                pay_day:day,
                                paid:paid,
                                amount:amount,
                                // amount:payregDetail[i].amount,
                                check_id:0,
                                success_at:0,
                                paytype_name:paytype_name,
                                create_name:this.create_name,
                                create_at:this.create_at,
                                check_time:this.salePayreg[key].paytype_id == 1 ? this.create_at : '',
                                status:4,
                                // payregDetail:payregDetail[i],
                                payregDetail:[],
                                isset:false,    // 在页面上追加的数据  标识 不是从数据表出来的数据，数据表操作是新增
                                key:key,     // 付款登记 head  table 的数据 索引下标
                                del_at:0,
                            })
                            if(this.payregList.length == 0){
                                this.payregList[this.payregList.length]['payregDetail'].push(payregDetail[i])
                            }else{
                                this.payregList[this.payregList.length-1]['payregDetail'].push(payregDetail[i])
                            }
                        } 
                        
                    }else{  // 判断是否现金登记
                        this.payregList.push({
                            viewid:this.payregList.length+1,
                            sale_id:this.data.saleOrderNo,
                            co_id:this.data.companyId,
                            paytype_id:this.salePayreg[key].paytype_id,
                            sale_payplan_id:this.salePayreg[key].id,
                            pay_day:pay_day,
                            paid:paid,
                            amount:amount,
                            check_id:0,
                            success_at:0,
                            paytype_name:paytype_name,
                            create_name:this.create_name,
                            create_at:this.create_at,
                            check_time:'',
                            status:4,
                            payregDetail:[],
                            isset:false,    // 在页面上追加的数据  标识 不是从数据表出来的数据，数据表操作是新增
                            key:key,     // 付款登记 head  table 的数据 索引下标
                            del_at:0,
                        })
                    }
            }
            // this.setPayreyHeadTable()
        },
        clickSalePayregRemark(key){
            $('#payregRemarksContent').val()
            this.getPublicInfo()
            this.publicInfo['paymentName'] = this.salePayreg[key]['content']
            this.publicInfo['paymentId'] = this.paymentList[key]['id']
            this.publicInfo['paymentAmount'] = this.salePayreg[key]['paymentAmount']
            this.publicInfo['paymentDay'] = this.salePayreg[key]['paymentDay']
            this.publicInfo['paytype_id'] = this.salePayreg[key]['paytype_id']
            this.publicInfo['key'] = key
            this.payregRemarkList = this.salePayreg[key]['remarksList']
        },
        setPayregRemarksList(){
            if(this.payregRemarkList == undefined) this.payregRemarkList = []
            this.payregRemarkList.push({
                content:$('#payregRemarksContent').val(),
                create_at:this.create_at,
                create_name:this.create_name,
                isset:false,
            })
            
        },
        savePayregRemarks(key){
            var j =0
            $.each(this.salePayreg[key],function(key,value){  
                if(key == 'remarksList') j=1
            });
            if(j==0) this.salePayreg[key]['remarksList'] = []
            this.salePayreg[key]['remarksList'] = this.payregRemarkList
            for (var i = 0; i < this.payregList.length; i++) {
                if( this.payregList[i]['key'] != undefined && this.payregList[i]['key'] == key){
                    this.payregList[i]['remarksList'] = []
                    this.payregList[i]['remarksList'] = this.payregRemarkList
                }
            }
        },
        _clickSalePayreg(){
            this.removeClassActive('#payreg_down_Modal',1)
            this.payperyViewShow(1,'_')
            this.payeryInputNull()
            this.payregAmount_ = 0
            this.voucherData_ = []
            this.PayeryChequeData_ = []
            this.payerytransferData_ = []
            this.fastPayrey_ = false

            this.point('','#payreg_down_Modal .alert','hide')

            this.getPublicInfo()
            this.publicInfo['key'] = -1

            // 代金券info
            this.getVoucher()
            this.getBank()
            this.getCoBank()
        },

        _savePayery(){
            var data = []
            data['payregDetail'] = []
            if( (!this.fastPayrey_ && this.payregAmount_) || (this.fastPayrey_  && this.fastPayrey_paytype_id == 1) ){
                data['paytype_id'] = 1;
                data['pay_day'] = this.create_at
                data['check_time'] = this.create_at
                data['paytype_name'] = '现金'
                this.__savePayery(data)
            }
            if(this.voucherData_.length > 0){
                data['paytype_id'] = 2;
                data['pay_day'] = this.create_at
                data['paytype_name'] = '代金券'
                data['payregDetail'] = this.voucherData_
                this.__savePayery(data)
            }
            if(this.PayeryChequeData_.length  > 0){
                data['paytype_id'] = 3;
                data['pay_day'] = this.create_at
                data['paytype_name'] = '现金支票/期票'
                data['payregDetail'] = this.PayeryChequeData_
                this.__savePayery(data)
            }
            if(this.payerytransferData_.length  > 0){
                data['paytype_id'] = 5;
                data['pay_day'] = this.create_at
                data['paytype_name'] = '转账'
                data['payregDetail'] = this.payerytransferData_
                this.__savePayery(data)
            }
        },

        __savePayery(data){
            if(this.payregList == undefined) {
                this.payregList = new Array();
            }
            if(data['paytype_id'] == 1){
                this.payregList.push({
                        viewid:this.payregList.length+1,
                        sale_id:this.data.saleOrderNo,
                        co_id:this.data.companyId,
                        paytype_id:data['paytype_id'],
                        sale_payplan_id:0,
                        pay_day:data['pay_day'],
                        paid:this.payregAmount_,
                        amount:this.payregAmount_,
                        check_id:0,
                        success_at:0,
                        paytype_name:data['paytype_name'],
                        create_name:this.create_name,
                        create_at:this.create_at,
                        check_time:'',
                        status:4,
                        payregDetail:[],
                        isset:false,    // 在页面上追加的数据  标识 不是从数据表出来的数据，数据表操作是新增
                        del_at:0,
                    })
            }else{

                for (var i = 0; i < data['payregDetail'].length; i++) {
                    var day = ''
                    if(data['paytype_id'] == 2){
                        day = this.create_at
                    }else if(data['paytype_id'] == 3 || data['paytype_id'] == 4){
                        day = data['payregDetail'][i]['chequeDay']
                    }else if(data['paytype_id'] == 5){
                        day = data['payregDetail'][i]['transferDay']
                    }
                    
                    this.payregList.push({
                        viewid:this.payregList.length+1,
                        sale_id:this.data.saleOrderNo,
                        co_id:this.data.companyId,
                        paytype_id:data['paytype_id'],
                        sale_payplan_id:0,
                        // pay_day:data['pay_day'],
                        pay_day: day,
                        paid:data['paytype_id'] == 2 ? data['payregDetail'][i]['amount'] : 0,
                        amount:data['paytype_id'] == 1 ? this.payregAmount_ : data['payregDetail'][i]['amount'],
                        check_id:0,
                        success_at:0,
                        paytype_name:data['paytype_name'],
                        create_name:this.create_name,
                        create_at:this.create_at,
                        check_time:'',
                        status:4,
                        // payregDetail:data['payregDetail'][i],
                        payregDetail:[],
                        isset:false,    // 在页面上追加的数据  标识 不是从数据表出来的数据，数据表操作是新增
                        del_at:0,
                    })
                    if(this.payregList.length == 0){
                        this.payregList[this.payregList.length]['payregDetail'].push(data['payregDetail'][i])
                    }else{
                        this.payregList[this.payregList.length-1]['payregDetail'].push(data['payregDetail'][i])
                    }
                    
                }
            }
            // this.setPayreyHeadTable()
        },
        // 送货单详情
        deliveryNoteDetail(key){
            this.deliveryNoteDetailData = this.deliveryNoteList[key]
        },
        deliveryNoteLock(id){
            $.ajax({
                url:'/admin/sale/deliveryNoteLock',
                type:'post',
                data:{id:id},
                success:(data)=>{
                    data = JSON.parse(data)
                    this.point(data.msg,'#alertMain','show',data.status)
                }
            })
        },
        
        // 保存订单
        saleOrderSave(is_back){
            this.point('','#main .alert','hide')
            if($('#requestType').val() == 'add'){
                var url = '/admin/sale/saleAdd?request=insert'
            }else{
                var url = '/admin/sale/saleEdit?request=update'
            }

            $.each(this.paymentList, (key1, value) => {
                if(value.paytype_id == 6 || value.paytype_id == 5){
                    this.salePayBill = 1;
                } 
            });
            
            // 判断 付款安排呵呵付款登记的付款方式 是不是在错误支付次数之内
            if(this.viewType == 'edit'){
                var is_ = this.is_payType()
                if(is_ != 1){
                    this.point(is_,'#main .alert','show')
                    return false
                }
            }
            if(this.salePayBill == 1 && this.data.receivingAccounId == 0){
                this.data.receivingAccounId = 0;
                this.point('付款安排有银行单/转账,必须选择一个指定收款账号','#main .alert','show')

            }else if(this.salePayBill == 1 && this.data.invoiceTypeId == 0){
                this.data.invoiceTypeId = 0;
                this.point('付款安排有银行单,必须选择一个指定发票类型','#main .alert','show')

            }else if (this.coSale.pledge && !this.data.pledge){
                this.point('当前所选客户必须选择 需要定金','#main .alert','show')

            }else if (this.coSale.makefirst && !this.data.makefirst){
                this.point('当前所选客户必须选择 先配货后结算','#main .alert','show')
            }else{

                // 完善销售订单存储数据
                this.data['total'] = this.billDate.price
                this.data['discount'] = this.billDate.discountPrice
                this.data['cost'] = this.billDate.costPrice
                this.data['pay'] = this.billDate.price - this.billDate.discountPrice
                this.data['commission'] = this.billDate.commissionPrice

                this.data['ctn'] = this.proCount.package_sum
                this.data['volume'] = this.proCount.m3

                this.data['accounts_id'] = this.data.receivingAccounId
                this.data['invoiceTypeId'] = this.data.invoiceTypeId == 0 || this.data.invoiceTypeId == undefined ? 0 : this.data.invoiceTypeId
                this.data['salePayBill'] = this.salePayBill == 0 || this.salePayBill == undefined ? 0 : this.salePayBill
                this.data['paid'] = this.billDate.payregPaid;
                var data=({
                    data:this.data,
                    saleOrderRemarkData:this.saleOrderRemarkData,
                    orderList:this.orderList,
                    costData:this.costData,
                    paymentList:this.paymentList,
                    payregList:this.payregList,
                    deliveryNoteList:this.deliveryNoteList,
                    delList:this.delList,
                    clearList:this.clearList

                })
                $.ajax({
                    url:url,
                    type:'post',
                    data,
                    success:(data)=>{
                        data = JSON.parse(data)
                        if(data.status == 1) {
                            if(is_back){
                                setTimeout(()=>{
                                    location.href="/admin/sale/list"
                                    window.localStorage.setItem("msg",data.msg)
                                },1000)
                            }else{
                                // 初始化data()
                                Object.assign(this.$data, this.$options.data())
                                this.getdata()
                            }
                            this.delList = []
                            // this.changeSaveTab()
                        }
                        this.point(data.msg,'#alertMain','show',data.status)
                    }
                })
            }
        },
        is_payType(){
            if(this.paymentList.length > 0){
                for (var i = 0; i < this.paymentList.length; i++) {
                    for (var j = 0; j < this.salePayType.length; j++) {
                        if(this.paymentList[i].paytype_id == this.salePayType[j].id && this.salePayType[j].fail > 0  && this.salePayType[j].fail >= this.salePayType[j].limit){
                            return '已选择的付款安排：'+this.salePayType[j].content+',付款失败次数已达上限，请重新选择付款方式'
                        }
                    }
                }
            }
            if(this.payregList.length > 0){
                for (var i = 0; i < this.payregList.length; i++) {
                    for (var j = 0; j < this.salePayType.length; j++) {
                        if(this.payregList[i].paytype_id == this.salePayType[j].id && this.salePayType[j].fail > 0 && this.salePayType[j].fail >= this.salePayType[j].limit){
                            return '已编辑的付款登记：'+this.salePayType[j].content+',付款失败次数已达上限，请重新编辑付款登记'
                        }
                    }
                }
            }

            return 1
            
        },
        point(msg,classText,type,status=0){
            change_mes_type(classText,status)
            if(type == 'show'){
                $(classText).show()
            }else{
                $(classText).hide()
            }
            $(classText+' p').html('*'+msg+'<br>')
        },
        // 弹框头部公共数据
        getPublicInfo(){
            this.publicInfo = []
            this.publicInfo['saleOrderNo'] = this.data.saleOrderNo
            var companyName = ''
            if(this.data.branchCompanyId){
                for (var i = 0; i < this.branchCompany.length; i++) {
                    if(this.branchCompany[i]['id'] == this.data.branchCompanyId) companyName = this.branchCompany[i]['name']
                }
            }else{
                for (var i = 0; i < this.company.length; i++) {
                    if(this.company[i]['id'] == this.data.companyId) companyName = this.company[i]['name']
                }
            }
            this.publicInfo['companyName'] = companyName
            this.publicInfo['companyId'] = this.data.branchCompanyId ? this.data.branchCompanyId : (this.data.companyId ? this.data.companyId : '')
        },




        removeClassActive(modelID,paytype_id){
            $(modelID+' li').removeClass('active');
            if(paytype_id == 1) $(modelID+" ul").children().eq(0).addClass('active')
            if(paytype_id == 2) $(modelID+" ul").children().eq(1).addClass('active')
            if(paytype_id == 3 || this.publicInfo.paytype_id == 4) $(modelID+" ul").children().eq(2).addClass('active')
            if(paytype_id == 5) $(modelID+" ul").children().eq(3).addClass('active')
            
        },
        // 弹框编辑删除
        modalEditAndDel(key,type,dataName){

            if(type == 'del' || type == 'clear'){

                var dataNameStr = 'delList'
                if(type == 'clear') var dataNameStr = 'clearList'
                // 判断是否删除已存入数据表的数据。
                if(this[dataName][key]['isset'] == undefined){
                    if(dataName == 'orderList' && this[dataName][key]['storeType'] == 'futures'){
                        if(this[dataNameStr]['futures'] == undefined) this[dataNameStr]['futures'] = []
                        this[dataNameStr]['futures'].push(this[dataName][key]['id']);
                    }else{
                        if(this[dataNameStr][dataName] == undefined) this[dataNameStr][dataName] = []
                        this[dataNameStr][dataName].push(this[dataName][key]['id']);    
                    }
                }


                this[dataName].splice(key,1)

                // 付款安排和 费用发生变化，产生的连锁事件
                if(dataName == 'paymentList' || dataName == 'costData'){
                    if(dataName == 'paymentList'){
                        $('#paymentAmountKey').val(-1)
                        if(this.paymentList.length == 0){
                            this.salePayBill = 0
                        }
                    } 
                    if(dataName == 'costData') $('#costPriceKey').val(-1)
                    this.setbillDateCostPrice()
                    this.setPaymentPrice_()
                }
            }

            if(type == 'edit'){
                // tab == 订单的 备注 编辑
                if( dataName == 'saleOrderRemarkData' ){
                    $('#orderRemarks').val(this[dataName][key]['content']);
                    $('#orderRemarksKey').val(key);
                }else if(dataName == 'addRemarksData'){     // tab == 产品 加工/备注

                    $('#remarksContent').val(this[dataName][key]['content']);
                    $('#remarksContentkey').val(key);

                    if( this[dataName][key]['private'] == true ){
                        $('#remarksTypePrivate').prop('checked',true)
                        $('#remarksTypePrivate').attr('checked','checked')
                    } 
                    if( this[dataName][key]['add'] == true ){
                        $('#remarksTypeAdd').prop('checked',true)
                        $('#remarksTypeAdd').attr('checked','checked')
                    } 
                    if( this[dataName][key]['rationed'] == true ){
                        $('#remarksTypeRationed').prop('checked',true)
                        $('#remarksTypeRationed').attr('checked','checked')
                    } 

                }else if(dataName == 'costData'){   // tab == 费用 编辑
                    $('#costPrice').val(this[dataName][key]['costPrice'])
                    $('#costRemarks').val(this[dataName][key]['costRemarks'])
                    $('#costPriceKey').val(key);

                    $.each(this.saleCostType, (key1, value) => {
                        if(value.id == this[dataName][key]['saleCostTypeId']){
                            $('#saleCostTypeIndex').val(key1)
                        } 
                    });
                    this.setbillDateCostPrice()
                    this.setPaymentPrice_()

                }else if(dataName == 'paymentList'){    // tab == 付款安排 编辑
                    $('#paymentAmountKey').val(key);
                    this.dayTime = ''
                    this.dayTime = this[dataName][key]['paymentDay']
                    $('#dayTime_').val(this[dataName][key]['paymentDay'])
                    $('#paydate').val(this[dataName][key]['paymentDay'])
                    $('#paymentAmount').val(this[dataName][key]['paymentAmount'])
                    $('#paymentPercentage').val( Math.round(this[dataName][key]['paymentPercentage']*100)/100 )

                    var days = this.daysBetween(this.create_at,this[dataName][key]['paymentDay']);
                    $('#paymentPayDay').val(days)

                    $.each(this.salePayType, (key1, value) => {
                        if(value.id == this[dataName][key]['paytype_id']){
                            $('#salePayType').val(key1)
                        } 
                    });
                    this.setPaymentPrice(this.dayTime)

                }else if(dataName == 'paymentRemarksDataList'){
                    $('#paymentRemarksContent').val(this[dataName][key]["content"])
                    $('#paymentRemarksContentKey').val(key)

                }else if(dataName == 'payregList'){// tab == 付款登记 编辑

                    this.publicInfo.paytype_id = this[dataName][key]['paytype_id']
                    this.payeryIsEdit = key
                    this.payregEdit = true
                    this.removeClassActive('#payreg_Modal',this.publicInfo.paytype_id)

                    if(this[dataName][key]['paytype_id'] == 1){
                        this.savePayeryPaytype_id=1
                    }else if(this[dataName][key]['paytype_id'] == 2){
                        
                        this.getVoucher()
                        $.each(this.voucherList, (key1, value) => {
                            if(value.id == this[dataName][key]['payregDetail'][0]['id']){
                                this.payregChequeInfo.voucherId = 0
                                this.payregChequeInfo.voucherId = key1
                            } 
                        });
                    }else if(this[dataName][key]['paytype_id'] == 3 || this[dataName][key]['paytype_id'] == 4){
                        this.getBank()
                        this.payregChequeInfo.chequeBankValue = -1
                        $.each(this.bankList, (keybankList, value) => {
                            if(value.id == this[dataName][key]['payregDetail'][0]['bank_id']){
                                this.payregChequeInfo.chequeBankValue = keybankList
                            } 
                        });
                        this.payregChequeInfo.chequeNoValue = this[dataName][key]['payregDetail'][0]['chequeNo'] 
                        this.payregChequeInfo.chequeSignature = this[dataName][key]['payregDetail'][0]['chequeSignature'] 
                        this.payregChequeInfo.chequeScan_url = this[dataName][key]['payregDetail'][0]['chequeScan_url'] 
                        this.payregChequeInfo.chequeDay = this[dataName][key]['payregDetail'][0]['chequeDay'] 
                        this.payregChequeInfo.chequePrice = this[dataName][key]['payregDetail'][0]['chequePrice'] 
                        this.payregChequeInfo.chequeNoKey = key

                    }else if(this[dataName][key]['paytype_id'] == 5){
                        this.getCoBank()
                        this.payregChequeInfo.chequeBankValue = -1
                        $.each(this.co_bank, (key1, value) => {
                            if(value.id == this[dataName][key]['payregDetail'][0]['transferOutId']){
                                this.payregChequeInfo.transferOutIdValue = key1
                                $('#transferOutId').val(key1)
                            } 
                        });
                        $.each(this.receivingAccount, (key1, value) => {
                            if(value.id == this[dataName][key]['payregDetail'][0]['transferInId']){
                                this.payregChequeInfo.transferInIdValue = key1
                                $('#transferInId').val(key1)
                            } 
                        });
                        this.payregChequeInfo.payreg_transfer_pay_dayValue = this[dataName][key]['payregDetail'][0]['transferDay'] 
                        this.payregChequeInfo.transferPriceValue = this[dataName][key]['payregDetail'][0]['transferPrice'] 
                        this.payregChequeInfo.transferNoValue = this[dataName][key]['payregDetail'][0]['transferNo'] 
                        this.payregChequeInfo.transferscan_url = this[dataName][key]['payregDetail'][0]['scan_url'] 
                        this.payregChequeInfo.transferKey = key
                    }
                }else if(dataName == 'setDeliveryNoteDetailData'){
                    $('#undoneQty').val(this[dataName][key]['undoneQty'])
                    $('#deliveryNoteProUndoneQty').val(this[dataName][key]['undone_qty'])
                    $('#deliveryNoteProQty').val(this[dataName][key]['qty'])
                    $('#undoneQtyKey').val(key)

                    $.each(this.orderList, (key1, value) => {
                        if(value.pro_id == this[dataName][key]['pro_id'] &&  value.prochar_id == this[dataName][key]['prochar_id']){
                            $('#deliveryNotePro').val(key1)
                        } 
                    });
                }else if(dataName == 'deliveryNoteRemarkContent'){
                    $('#deliveryNoteContent').val(this[dataName][key]['content'])
                    $('#deliveryNoteContentKey').val(key)

                }else if(dataName == 'deliveryNoteList'){
                    $('#undoneQty').val(this[dataName][key]['undoneQty'])
                    $('#deliveryNoteProUndoneQty').val(this[dataName][key]['undone_qty'])
                    $('#deliveryNoteProQty').val(this[dataName][key]['qty'])
                    $('#undoneQtyKey').val(key)

                    $.each(this.orderList, (key1, value) => {
                        if(value.pro_id == this[dataName][key]['pro_id'] &&  value.prochar_id == this[dataName][key]['prochar_id']){
                            $('#deliveryNotePro').val(key1)
                        } 
                    });
                }
            }
        },
        getBank(){
            $.ajax({
                url:'/admin/sale/list?request=getBank',
                type:'post',
                success:(data)=>{
                    data = JSON.parse(data)
                    this.bankList = data
                }
            })
        },
        getCoBank(){
            var company_id = this.data.branchCompanyId ? this.data.branchCompanyId : this.data.companyId 
            $.ajax({
                url:'/admin/sale/list?request=co_bank&company_id='+this.data.companyId,
                type:'post',
                success:(data)=>{
                    data = JSON.parse(data)
                    this.co_bank = data
                }
            })
        },
        getVoucher(){
            var company_id = this.data.branchCompanyId ? this.data.branchCompanyId : this.data.companyId 
            $.ajax({
                url:'/admin/sale/list?request=getVoucher&company_id=' + company_id,
                type:'post',
                success:(data)=>{
                    data = JSON.parse(data)
                    this.voucherList = data
                }
            })
        },
        getInvoiceType(){

            if($('#requestType').val() == 'add'){
                var url = '/admin/sale/saleAdd?request=invoiceType'
            }else{
                var url = '/admin/sale/saleEdit?request=invoiceType'
            }
            $.ajax({
                url:url,
                type:'post',
                success:(data)=>{
                    data = JSON.parse(data)
                    this.getInvoiceTypeList = data
                }
            })
            
        },
        // 暂停保存按钮
        changeSaveTab(){
            $('#changeSaveTab').attr('disabled',true)
        },
        // 付款安排--付款日期根据间隔自动计算
        payDayCalculate(intervalDay_=0){
            if($('#paymentPayDay').val().indexOf('.') != -1){
                $('#paymentPayDay').val(Math.ceil($('#paymentPayDay').val()))
            }
            $('#paymentPayDay').val( parseInt($('#paymentPayDay').val()) )
            var intervalDay = 0
            if(intervalDay_==0){
                intervalDay = $('#paymentPayDay').val()
            }else{
                intervalDay = intervalDay_
            } 
            // 年
            var year = this.year
            // 月
            var month = this.month

            if(intervalDay == 0){
                this.dayTime = this.create_at
            } else{
                this.dayTime = this.countDate(year+'-'+month+'-'+this.taday,intervalDay)
            }
            if(intervalDay_ > 0 ) return this.dayTime
            
        },
        countDate(datt,n){
            datt = datt.split('-');
            var newDate = new Date(datt[0], datt[1] - 1, datt[2]);
            var befminuts = newDate.getTime() + 1000 * 60 * 60 * 24 * parseInt(n);//计算前几天用减，计算后几天用加，最后一个就是多少天的数量 n为向前或者向后天数
            var beforeDat = new Date;
            beforeDat.setTime(befminuts);
            var befMonth = beforeDat.getMonth() + 1;
            var mon = befMonth >= 10 ? befMonth : '0' + befMonth;
            var befDate = beforeDat.getDate();
            var da = befDate >= 10 ? befDate : '0' + befDate;
            var newDate = beforeDat.getFullYear() + '-' + mon + '-' + da;
            return newDate
        },


        // 付款登记 未保存数据编辑
        payeryClickEdit(key,dataName){
            if(dataName == 'payerytransferData_' || dataName == 'payerytransferData'){
                var idName = dataName == 'payerytransferData' ? '' : '_'
                $('#transferOutId'+idName).val(this[dataName][key].transferOutKey)
                $('#transferDay'+idName).val(this[dataName][key].transferDay)
                $('#transferInId'+idName).val(this[dataName][key].transferInKey)
                $('#transferPrice'+idName).val(this[dataName][key].transferPrice)
                $('#transferNo'+idName).val(this[dataName][key].transferNo)
                $('#transfereditKey'+idName).val(key)
            }else if(dataName == 'PayeryChequeData_' || dataName == 'PayeryChequeData'){
                var idName = dataName == 'PayeryChequeData' ? '' : '_'
                $('#chequeBank_'+idName).val(this[dataName][key].bank_key)
                $('#chequeNo'+idName).val(this[dataName][key].chequeNo)
                $('#chequeSignature'+idName).val(this[dataName][key].chequeSignature)
                $('#chequePrice'+idName).val(this[dataName][key].chequePrice)
                $('#chequeDay'+idName).val(this[dataName][key].chequeDay)
                $('#chequeScan_url'+idName).val(this[dataName][key].chequeScan_url)
                $('#chequeNoEditKey'+idName).val(key)
            }
            
        },
        payeryInputNull(){
            $('#payregAmount').val('')
            $('#payregAmount_').val('')
            $('#voucher').val(-1)
            $('#voucher_').val(-1)
            $('#chequeBank').val(-1)
            $('#chequeBank_').val(-1)
            $('#chequeNo').val('')
            $('#chequeNo_').val('')
            $('#chequeSignature').val('')
            $('#chequeSignature_').val('')
            $('#chequePrice').val('')
            $('#chequePrice_').val('')
            $('#transferOutId').val(-1)
            $('#transferOutId_').val(-1)
            $('#transferInId').val(-1)
            $('#transferInId_').val(-1)
            $('#transferPrice').val('')
            $('#transferPrice_').val('')
            $('#transferNo').val('')
            $('#transferNo_').val('')
            $('#chequeScan_url').val('')
            $('#chequeScan_url_').val('')
            $('#transferScan_url').val('')
            $('#transferScan_url_').val('')
            this.payregChequeInfo.chequeBankValue = -1
            this.payregChequeInfo.chequeNoValue = ''
            this.payregChequeInfo.chequeSignature = ''
        },
        //设置popper组件的配置
        setpopper(e){
            $(e.target).popover({
                trigger: 'hover focus manual',
                placement: ($(e.target).attr("placement") == undefined) ? 'left' : $(e.target).attr("placement"),
                //placement:'left',
                title: $(e.target).attr("title"),
                html: 'true',
                content: $(e.target).find(".content").html(),
                animation: false
            });
        },
        // 判断两个日期之间相差多少天
        daysBetween(sDate1,sDate2){
            //Date.parse() 解析一个日期时间字符串，并返回1970/1/1 午夜距离该日期时间的毫秒数
            var time1 = Date.parse(new Date(sDate1));
            var time2 = Date.parse(new Date(sDate2));
            // var nDays = Math.abs(parseInt((time2 - time1)/1000/3600/24));
            var nDays = (parseInt((time2 - time1)/1000/3600/24));
            return nDays;
        },
        fanhui(){
                window.history.go(-1)
        },
    },
    mounted(){
        $('#changeSaveTab').attr('disabled',false)
        this.getdata()
        var create_at = this.myDate.getFullYear() + '-' + (this.myDate.getMonth()+1) + '-' + this.myDate.getDate()
        this.create_at = create_at
        this.saleList.create_time = create_at

        this.taday = this.myDate.getDate()

        this.myDate.setMonth(this.myDate.getMonth()+1);
        this.myDate.setDate(0);
        this.lastData = new Date(this.myDate).getDate()
        // 年
        this.year = this.myDate.getFullYear()
        // 月
        this.month = this.myDate.getMonth()+1

        this.create_name = $('#create_name').val()
        // 导航栏选中
        if( $('#tab').val() ){
            var obj = $("#headnav .nav li");          
            if(obj.length>0)
            {
                $.each(obj, function (index, value)
                {
                    if($(value).hasClass("active") && $(value).children('a').attr('href') != ('#'+$('#tab').val()) ) {
                        $(value).removeClass("active");
                    }else {
                        if($(value).children('a').attr('href') == ('#'+$('#tab').val()) ){
                            $(value).addClass('active');
                        }
                    }
                })
            }
            var obj_ = $("#indexcontent div")
            if($("#indexcontent div").length>0)
            {
                $.each(obj_, function (index1, value1){
                    if($(value1).hasClass("active") && $(value1).attr('id') != $('#tab').val() ) {
                        $(value1).removeClass("active");
                    }else {
                        if($(value1).attr('id') == $('#tab').val() ){
                            $(value1).addClass('active');
                        }
                    }
                })
            }

            $('#payreg_cash_').addClass('active');
            $('#payreg_cash_head').addClass('active');
        }
        $('#paydate').change(function(){
            var newval = $('#paydate').val()
            oldval=create_at
            var starttime = (new Date(newval).getTime().toString()).substr(0,10)-8*60*60;
            var endtime = (new Date(oldval).getTime().toString()).substr(0,10);
            var chatime=starttime-endtime;
            if(chatime==0){
                days=0;
            }else {
                days=chatime/86400
            }
            if(days < 0) {
                change_mes_type('#alertMain',2)
                $('#alertMain').show()
                $('#alertMain p').html('*付款安排时间不能早于当天<br>')
                return false
            }else{
                $('#alertMain').hide()
            }
            $('#paymentPayDay').val(Math.ceil(days))
        })
    },
    computed:{
        //计算合计
        sumnum(){
            var s = 0;
            var m = 0;
            var w = 0;
            if(this.deliveryNoteDetailData.salePackData != undefined){
                this.deliveryNoteDetailData.salePackData.forEach(e => {
                    s+= Number(e.ctns);//箱数
                    m+= Number(e.volume*e.ctns);//每一个箱号的体积*箱数
                    w+= Number(e.ctn_kgs);//重量
                });    
            }
            return [s,m,w];
        }
    },

})

    
